<template>
  <view class="page-container">
    <!-- 顶部标题区 -->
    <view class="top-title">
      <text class="welcome-text">你好，欢迎登录</text>
      <text class="platform-name">蓟城山水全域智能运营管理平台</text>
    </view>

    <!-- 登录表单区域 -->
    <view class="login-form">
      <!-- 登录方式切换 -->
      <up-tabs
          :list="tabList"
          line-width="55"
          line-height="2"
          @change="handleTabChange"
          :activeStyle="{ color: '#3c9cff', fontWeight:'500', fontSize: '14px' }"
          :inactiveStyle="{ color: '#606060', fontSize: '14px' }"
      ></up-tabs>

      <!-- 表单校验容器 -->
      <up-form
          label-position="left"
          :model="form"
          ref="loginFormRef"
          labelWidth="0"
      >
        <!-- ========== 手机号登录区域 ========== -->
        <view v-if="loginType === '手机号登录'">
          <!-- 手机号输入框 -->
          <up-form-item prop="mobile">
            <up-input
                v-model="form.mobile"
                border="surround"
                maxlength="11"
                input-align="left"
                fontSize="14px"
                :disabled="isLoading"
                shape="circle"
                placeholder="请输入手机号"
                @blur="() => loginFormRef.validateField('mobile')"
            />
          </up-form-item>

          <!-- 验证码输入框 + 自定义倒计时按钮 -->
          <up-form-item prop="code">
            <up-input
                v-model="form.code"
                border="surround"
                maxlength="4"
                type="number"
                input-align="left"
                fontSize="14px"
                :disabled="isLoading"
                shape="circle"
                placeholder="请输入验证码"
                @blur="() => loginFormRef.validateField('code')"
            >
              <template #suffix>
                <up-button
                    size="mini"
                    type="primary"
                    :disabled="isCodeBtnDisabled"
                    :loading="isCodeLoading"
                    @tap="getVerificationCode"
                    shape="circle"
                >
                  {{ countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码' }}
                </up-button>
              </template>
            </up-input>
          </up-form-item>
        </view>

        <!-- ========== 账号登录区域 ========== -->
        <view v-else>
          <!-- 账号输入框 -->
          <up-form-item prop="account">
            <up-input
                v-model="form.account"
                border="surround"
                maxlength="30"
                input-align="left"
                fontSize="14px"
                :disabled="isLoading"
                shape="circle"
                placeholder="请输入账户"
                @blur="() => loginFormRef.validateField('account')"
            />
          </up-form-item>

          <!-- 密码输入框 -->
          <up-form-item prop="password" class="password-item">
            <up-input
                v-model="form.password"
                placeholder="请输入密码"
                maxlength="20"
                border="surround"
                input-align="left"
                type="password"
                :disabled="isLoading"
                shape="circle"
                @blur="() => loginFormRef.validateField('password')"
            />
          </up-form-item>

          <!-- 记住密码 -->
          <view class="remember-wrap">
            <up-checkbox
                :customStyle="{marginBottom: '8px'}"
                label="记住密码"
                name="agree"
                size="14"
                iconSize="14"
                labelSize="14"
                labelColor="#3F3F3F"
                usedAlone
                v-model:checked="rememberPwd"
            >
            </up-checkbox>
          </view>
        </view>
      </up-form>

      <!-- 登录按钮 -->
      <up-button
          class="login-btn"
          type="primary"
          size="large"
          :loading="isLoading"
          @click="handleLogin"
          shape="circle"
      >
        登录
      </up-button>
    </view>

    <!-- 版权信息 -->
    <view class="copyright">蓟城山水集团版权所有</view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed, onUnmounted} from 'vue';
import {onShow} from '@dcloudio/uni-app'
import { useUserStore } from '@/pinia/user';
import globalConfig from '@/common/config/global';
import CryptoJS from 'crypto-js';
import { getSmsCode } from "@/api/user";

// ========== 加密工具函数 ==========
const CRYPTO_CONFIG = {
  key: CryptoJS.enc.Utf8.parse('jcsscrypto123abc'), // 16位key
  iv: CryptoJS.enc.Utf8.parse('abc123jcsscrypto'),  // 16位iv
  mode: CryptoJS.mode.CBC,
  padding: CryptoJS.pad.Pkcs7
};

const aesEncrypt = (text) => {
  if (!text) return '';
  try {
    return CryptoJS.AES.encrypt(text, CRYPTO_CONFIG.key, {
      iv: CRYPTO_CONFIG.iv,
      mode: CRYPTO_CONFIG.mode,
      padding: CRYPTO_CONFIG.padding
    }).toString();
  } catch (err) {
    console.error('AES加密失败:', err);
    return '';
  }
};

const aesDecrypt = (encryptedText) => {
  if (!encryptedText) return '';
  try {
    const decryptObj = CryptoJS.AES.decrypt(encryptedText, CRYPTO_CONFIG.key, {
      iv: CRYPTO_CONFIG.iv,
      mode: CRYPTO_CONFIG.mode,
      padding: CRYPTO_CONFIG.padding
    });
    return decryptObj.toString(CryptoJS.enc.Utf8);
  } catch (err) {
    console.error('AES解密失败:', err);
    return '';
  }
};

// ========== 核心业务逻辑 ==========
const userStore = useUserStore();
const loginFormRef = ref(null);
const isLoading = ref(false);
const isCodeLoading = ref(false); // 验证码按钮独立loading状态

// 登录方式切换
const tabList = ref([{ name: '手机号登录' }, { name: '账号登录' }]);
const loginType = ref('手机号登录');

// 记住密码（仅账号登录生效）
const rememberPwd = ref(true);

// 表单数据
const form = reactive({
  account: '',  // 账号
  mobile: '',   // 手机号
  password: '', // 密码
  code: ''      // 验证码
});

// 验证码倒计时相关
const countdown = ref(0);
let countdownTimer = null; // 倒计时定时器

// 临时缓存KEY
const TEMP_FORM_KEY = 'login_temp_form_data';

// ========== 方案二核心：保存/恢复表单数据 ==========
// 保存表单数据到本地缓存
const saveFormData = () => {
  try {
    const tempData = {
      form: { ...form },
      loginType: loginType.value,
      countdown: countdown.value,
      rememberPwd: rememberPwd.value
    };
    // 加密存储，提升安全性
    const encryptData = aesEncrypt(JSON.stringify(tempData));
    uni.setStorageSync(TEMP_FORM_KEY, encryptData);
  } catch (err) {
    console.warn('保存表单数据失败:', err);
  }
};

// 从本地缓存恢复表单数据
const restoreFormData = () => {
  try {
    const encryptData = uni.getStorageSync(TEMP_FORM_KEY);
    if (!encryptData) return;

    const tempData = JSON.parse(aesDecrypt(encryptData));
    // 恢复表单数据
    if (tempData.form) {
      Object.assign(form, tempData.form);
    }
    // 恢复登录类型
    // if (tempData.loginType) {
    //   loginType.value = tempData.loginType;
    // }
    // 恢复记住密码状态
    if (tempData.rememberPwd !== undefined) {
      rememberPwd.value = tempData.rememberPwd;
    }
    // 恢复倒计时
    if (tempData.countdown && tempData.countdown > 0) {
      countdown.value = tempData.countdown;
      // 重启倒计时定时器
      startCountdown(countdown.value);
    }

    // 恢复记住密码的缓存数据（原有逻辑）
    if (rememberPwd.value && loginType.value === '账号登录') {
      const savedAccount = aesDecrypt(uni.getStorageSync('login_account') || '');
      const savedPwd = aesDecrypt(uni.getStorageSync('login_password') || '');
      if (savedAccount) {
        form.account = savedAccount;
        form.password = savedPwd;
      }
    }
  } catch (err) {
    console.warn('恢复表单数据失败:', err);
  }
};

// 校验手机号格式
const isMobileValid = computed(() => {
  const mobileReg = /^1[3-9]\d{9}$/;
  return mobileReg.test(form.mobile);
});

// 统一计算验证码按钮禁用状态
const isCodeBtnDisabled = computed(() => {
  return countdown.value > 0 || isLoading.value || isCodeLoading.value || !isMobileValid.value;
});

// 表单校验规则
const loginFormRules = reactive({
  account: [
    { type: 'string', required: true, message: '请输入登录账号', trigger: ['change', 'blur'] },
    { type: 'string', min: 2, max: 30, message: '账号长度为2-30个字符', trigger: ['change', 'blur'] }
  ],
  mobile: [
    { type: 'string', required: true, message: '请输入手机号', trigger: ['change', 'blur'] },
    { type: 'string', pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: ['change', 'blur'] }
  ],
  password: [
    { type: 'string', required: true, message: '请输入登录密码', trigger: ['change', 'blur'] },
    { type: 'string', min: 3, max: 20, message: '密码长度为3-20个字符', trigger: ['change', 'blur'] }
  ],
  code: [
    { type: 'string', required: true, message: '请输入验证码', trigger: ['change', 'blur'] },
    { type: 'string', len: 4, message: '验证码长度4位', trigger: ['change', 'blur'] }
  ]
});

// 切换登录方式
const handleTabChange = ({ name }) => {
  if (isLoading.value) return;

  loginType.value = name;
  // 清空校验状态和无关输入框
  nextTick(() => {
    loginFormRef.value?.clearValidate();
  });
};

// 开始验证码倒计时
const startCountdown = (seconds = 60) => {
  countdown.value = seconds;

  // 清除已有定时器，避免重复
  if (countdownTimer) clearInterval(countdownTimer);

  countdownTimer = setInterval(() => {
    if (countdown.value <= 0) {
      clearCountdown();
      return;
    }
    countdown.value--;
  }, 1000);
};

// 清除倒计时
const clearCountdown = () => {
  countdown.value = 0;
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
};

// 获取验证码
const getVerificationCode = async () => {
  // 双重校验：按钮禁用状态
  if (isCodeBtnDisabled.value) {
    console.warn('验证码按钮已禁用，不执行请求');
    return;
  }

  try {
    isCodeLoading.value = true; // 按钮进入loading
    uni.showLoading({ title: '发送验证码中...', mask: true }); // 遮罩防止重复点击

    const postData = {
      mobile: form.mobile,
      scene: 21
    };
    // 调用验证码接口
    const res = await getSmsCode(postData);

    uni.hideLoading();
    uni.$u.toast('验证码已发送，请注意查收');
    startCountdown(); // 仅接口成功时开始倒计时
  } catch (err) {
    // 捕获接口异常
    uni.hideLoading();
    console.error('获取验证码失败:', err);
    uni.$u.toast(err.msg || '发送验证码失败，请重试');
  } finally {
    isCodeLoading.value = false; // 结束loading状态
  }
};

// 检查登录状态
const checkLoginStatus = () => {
  try {
    if (userStore.isLogin) {
      uni.switchTab({
        url: '/pages/workbench/index',
        fail: () => uni.reLaunch({ url: '/pages/workbench/index' })
      });
    }
  } catch (err) {
    console.warn('检查登录状态失败:', err);
  }
};

// 登录处理
const handleLogin = async () => {
  try {
    // 根据登录类型校验对应字段
    const validateFields = loginType.value === '手机号登录'
        ? ['mobile', 'code']
        : ['account', 'password'];

    // 执行表单校验
    const validateRes = await loginFormRef.value.validate(validateFields);
    if (!validateRes) {
      return;
    }

    isLoading.value = true;

    // 组装登录参数
    const loginParams = {};
    if (loginType.value === '手机号登录') {
      loginParams.mobile = form.mobile;
      loginParams.code = form.code;
      loginParams.type = 'sms';
    } else {
      loginParams.username = form.account;
      loginParams.password = form.password;
      loginParams.type = 'password';
    }

    // 执行登录
    await userStore.login(loginParams);

    // 保存登录信息（仅账号登录且勾选记住密码）
    if (loginType.value === '账号登录' && rememberPwd.value) {
      try {
        uni.setStorageSync('login_account', aesEncrypt(form.account));
        uni.setStorageSync('login_password', aesEncrypt(form.password));
        uni.removeStorageSync('login_mobile');
      } catch (err) {
        console.warn('保存登录信息失败:', err);
      }
    } else {
      // 清除缓存
      uni.removeStorageSync('login_account');
      uni.removeStorageSync('login_mobile');
      uni.removeStorageSync('login_password');
    }

    // 登录成功后清除临时表单缓存
    uni.removeStorageSync(TEMP_FORM_KEY);

    // 登录成功跳转
    uni.showToast({ title: '登录成功', icon: 'success', duration: 1000 });
    setTimeout(() => {
      uni.switchTab({
        url: globalConfig.router.tabBarList[1].path,
        fail: () => uni.reLaunch({ url: '/pages/workbench/index' })
      });
    }, 1000);
  } catch (err) {
    console.error('登录失败:', err);
    uni.showToast({
      title: err.msg || (loginType.value === '手机号登录' ? '验证码错误' : '账号或密码错误'),
      icon: 'none',
      duration: 1000
    });
  } finally {
    isLoading.value = false;
  }
};

// ========== 小程序生命周期适配（方案二核心） ==========
// 页面显示时（切回页面）恢复数据
onShow(() => {
  restoreFormData();
});

// 页面卸载时保存数据
onUnmounted(() => {
  clearCountdown();
  saveFormData();
});

// 页面挂载时初始化
onMounted(() => {
  checkLoginStatus();

  // 初始化表单规则
  nextTick(() => {
    loginFormRef.value?.setRules(loginFormRules);
    // 首次挂载也恢复一次数据
    restoreFormData();
  });
});
</script>

<style scoped lang="scss">
.page-container {
  height: 100vh;
  background: url("https://img.jichengshanshui.com.cn:28207/appimg/loginbg.jpg") no-repeat;
  background-position: bottom center;
  background-size: 100% 240px;
}

.top-title {
  background: url("https://img.jichengshanshui.com.cn:28207/appimg/bg.jpg") no-repeat;
  background-size: 100% 100%;
  color: #fff;
  padding: 200rpx 0 200rpx 40rpx;
  text-align: left;
  position: relative;
  z-index: 1;

  .welcome-text {
    font-size: 20px;
    display: block;
    margin-bottom: 10px;
  }

  .platform-name {
    margin-bottom: 10px;
    font-size: 20px;
    display: block;
  }
}

.login-form {
  background-color: #fff;
  padding: 20px 15px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
  margin: -90px 20px 0;
  position: relative;
  z-index: 10;
  box-sizing: border-box;
}

:deep(.u-tabs) {
  margin-bottom: 15px;

  .u-tabs__content {
    height: auto !important;
  }

  .u-tab-item {
    padding: 0 10px;
  }
}

:deep(.u-form-item) {
  margin-bottom: 10px;
  position: relative;
}

.password-item {
  position: relative;
  margin-bottom: 5px !important;
}

.remember-wrap {
  padding: 0;
  margin: 10px 0 20px;

  :deep(.u-checkbox) {
    font-size: 12px;
    color: #666;
    justify-content: flex-end;
    margin-left: 0 !important;

    .u-checkbox__label {
      margin-left: 5px;
    }
  }
}

.login-btn {
  margin-top: 10px;
  width: 100%;
  height: 44px;
  line-height: 44px;
  border-radius: 4px;
  font-size: 18px;
  background: #0A86F4;
  box-shadow: 0px 4px 6px 1px rgba(25,94,215,0.5);
  border-radius: 23px;
}

.copyright {
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: #999;
  position: fixed;
  bottom: 60px;
}

// 验证码按钮样式优化
:deep(.u-input__suffix) {
  padding-right: 10rpx;
}

:deep(.u-button--mini) {
  height: 60rpx;
  line-height: 60rpx;
  padding: 0 15rpx;
}
</style>