<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-content">
        <div class="login-header">
          <h2>欢迎登录</h2>
          <p class="sub-title">请输入您的账号信息</p>
        </div>
        
        <a-form 
          ref="loginForm"
          :model="formData"
          :rules="rules"
          layout="vertical"
        >
          <!-- 账号密码登录表单 -->
          <template v-if="loginType === 'account'">
            <a-form-item label="账号" name="username">
              <a-input
                v-model:value="formData.username"
                placeholder="请输入账号"
                size="large"
              >
                <template #prefix>
                  <UserOutlined style="color: rgba(0,0,0,.25)" />
                </template>
              </a-input>
            </a-form-item>
            
            <a-form-item label="密码" name="password">
              <a-input-password
                v-model:value="formData.password"
                placeholder="请输入密码"
                size="large"
              >
                <template #prefix>
                  <LockOutlined style="color: rgba(0,0,0,.25)" />
                </template>
              </a-input-password>
            </a-form-item>
            <a-form-item label="商户编码" name="merchant_code">
              <a-input
                v-model:value="formData.merchant_code"
                placeholder="请输入商户编码"
                size="large"
              ></a-input>
            </a-form-item>
          </template>

          <!-- 手机号登录表单 -->
          <template v-else-if="loginType === 'mobile'">
            <a-form-item label="手机号" name="mobile">
              <a-input
                v-model:value="formData.mobile"
                placeholder="请输入手机号"
                size="large"
              >
                <template #prefix>
                  <MobileOutlined style="color: rgba(0,0,0,.25)" />
                </template>
              </a-input>
            </a-form-item>
            
            <a-form-item label="验证码" name="verification_code">
              <div class="verification-code-input">
                <a-input
                  v-model:value="formData.verification_code"
                  placeholder="请输入验证码"
                  size="large"
                >
                  <template #prefix>
                    <SafetyCertificateOutlined style="color: rgba(0,0,0,.25)" />
                  </template>
                </a-input>
                <a-button 
                  :disabled="!!countdown || !formData.mobile"
                  @click="sendVerificationCode"
                  size="large"
                >
                  {{ countdown ? `${countdown}秒后重试` : '获取验证码' }}
                </a-button>
              </div>
            </a-form-item>
          </template>

          <!-- 微信登录表单 -->
          <template v-if="loginType === 'wechat'">
            <div class="wechat-login-container">
              <div v-if="wechatQrCode" class="wechat-qrcode-wrapper">
                <img 
                  :src="wechatQrCode" 
                  alt="微信登录二维码"
                  class="wechat-qrcode"
                />
                <p class="qrcode-tip">请使用微信扫描二维码登录</p>
                <p class="qrcode-sub-tip">扫码后请在微信中确认登录</p>
              </div>
              <div v-else class="qrcode-loading">
                <a-spin tip="正在加载二维码..." />
              </div>
            </div>
          </template>
          
          <div class="form-options">
            <a-checkbox v-model:checked="rememberMe">记住账号</a-checkbox>
            <router-link to="/forget-password" class="forgot-password">忘记密码？</router-link>
          </div>
          
          <a-form-item>
            <a-button 
              type="primary" 
              :loading="loading"
              size="large"
              block
              @click="handleLogin"
            >
              登录
            </a-button>
          </a-form-item>
        </a-form>

        <div class="login-footer">
          <!-- <p class="register-tip">
            还没有账号？<router-link to="/register" class="register-link">立即注册</router-link>
          </p> -->
          
          <!-- 登录方式切换移动到这里 -->
          <!-- <div class="login-type-switch">
            <p class="switch-title">切换登录方式</p>
            <a-radio-group v-model:value="loginType" button-style="solid">
              <a-radio-button value="account">账号密码登录</a-radio-button>
              <a-radio-button value="mobile">手机验证码登录</a-radio-button>
            </a-radio-group>
          </div> -->

          <div class="other-login">
            <div class="divider">
              <span>其他登录方式</span>
            </div>
            <div class="social-login">
              <a-tooltip title="微信登录">
                <WechatOutlined 
                  class="social-icon"
                  :class="{ active: loginType === 'wechat' }"
                  @click="switchToWechatLogin"
                />
              </a-tooltip>
              <a-tooltip title="QQ登录">
                <QqOutlined class="social-icon" />
              </a-tooltip>
              <a-tooltip title="钉钉登录">
                <DingdingOutlined class="social-icon" />
              </a-tooltip>
              <a-tooltip v-if="loginType === 'account'" title="手机号登录">
                <MobileOutlined 
                  class="social-icon" 
                  @click="switchToMobileLogin"
                />
              </a-tooltip>
              <a-tooltip v-else title="账号密码登录">
                <UserOutlined 
                  class="social-icon" 
                  @click="switchToAccountLogin"
                />
              </a-tooltip>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 微信登录弹窗 -->
    <a-modal
      v-model:visible="wechatLoginModal"
      title="微信扫码登录"
      :footer="null"
      @cancel="handleWechatLoginCancel"
      width="360px"
      centered
    >
      <div class="wechat-qrcode-container">
        <img 
          :src="wechatQrCode" 
          alt="微信登录二维码"
          class="wechat-qrcode"
        />
        <p class="qrcode-tip">请使用微信扫描二维码登录</p>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, reactive, ref, nextTick, onUnmounted, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import axios from 'axios';
import { message, Modal } from 'ant-design-vue';
import { 
  UserOutlined, 
  LockOutlined,
  WechatOutlined,
  QqOutlined,
  DingdingOutlined,
  MobileOutlined,
  SafetyCertificateOutlined
} from '@ant-design/icons-vue';

export default defineComponent({
  name: 'login',
  components: {
    UserOutlined,
    LockOutlined,
    WechatOutlined,
    QqOutlined,
    DingdingOutlined,
    MobileOutlined,
    SafetyCertificateOutlined
  },
  setup() {
    const store = useStore();
    const router = useRouter();
    const loginForm = ref();
    const loading = ref(false);
    const rememberMe = ref(false);
    const loginType = ref('account'); // 登录方式：'account', 'mobile', 'wechat'
    const countdown = ref(0); // 验证码倒计时
    
    const formData = reactive({
      username: '',
      password: '',
      merchant_code: '',//E20250212000624fd2a92
      mobile: '',
      verification_code: ''
    });
    
    const rules = {
      username: [
        { required: true, message: '请输入账号' },
        { min: 4, message: '账号长度不能小于4位' }
      ],
      password: [
        { required: true, message: '请输入密码' },
        { min: 6, message: '密码长度不能小于6位' }
      ],
      merchant_code: [
        { required: true, message: '请输入商户编码' },
        { min: 1, message: '商户编码长度不能小于1位' }
      ],
      mobile: [
        { required: true, message: '请输入手机号' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
      ],
      verification_code: [
        { required: true, message: '请输入验证码' },
        { len: 6, message: '验证码长度必须为6位' }
      ]
    };

    // 发送验证码
    const sendVerificationCode = async () => {
      try {
        // 验证手机号
        await loginForm.value.validateFields(['mobile']);
        
        const response = await axios.post(`${import.meta.env.VITE_BASE_AI_API}/user/send_verification_code`, {
          mobile: formData.mobile,
          merchant_code: formData.merchant_code
        });

        if (response.data.code === 200) {
          message.success('验证码发送成功');
          // 开始倒计时
          countdown.value = 60;
          const timer = setInterval(() => {
            countdown.value--;
            if (countdown.value <= 0) {
              clearInterval(timer);
            }
          }, 1000);
        } else {
          message.error(response.data.message || '验证码发送失败');
        }
      } catch (error) {
        console.error('验证码发送失败:', error);
        message.error(error.response?.data?.message || '验证码发送失败');
      }
    };

    // 处理登录
    const handleLogin = async () => {
      try {
        loading.value = true;
        await loginForm.value.validate();
        
        let response;
        if (loginType.value === 'account') {
          // 账号密码登录
          response = await axios.post(`${import.meta.env.VITE_BASE_AI_API}/user/login`, {
            username: formData.username,
            password: formData.password,
            merchant_code: formData.merchant_code
          });
        } else if (loginType.value === 'mobile') {
          // 手机验证码登录
          response = await axios.post(`${import.meta.env.VITE_BASE_AI_API}/user/mobile_login`, {
            mobile: formData.mobile,
            verification_code: formData.verification_code,
            merchant_code: formData.merchant_code
          });
        } else {
          // 微信登录
          response = await axios.post(`${import.meta.env.VITE_BASE_AI_API}/user/wechat_login`, {
            wechat_state: formData.wechat_state
          });
        }

        if (response.data.code === 200) {
          // 保存token到localStorage
          localStorage.setItem('token', response.data.data.token);
          
          // 获取用户详细信息
          try {
            const userInfoResponse = await axios.get(`${import.meta.env.VITE_BASE_AI_API}/user/info`, {
              headers: {
                'Authorization': `JWT ${response.data.data.token}`
              }
            });
            console.log(userInfoResponse);
            if (userInfoResponse.data.code === 200) {
              // 存储用户信息和权限到 Vuex store
              store.commit('app/setUser', {
                user: userInfoResponse.data.data,
                permission: userInfoResponse.data.data || [],
              });

              // 同时存储到 localStorage
              localStorage.setItem('userInfo', JSON.stringify(userInfoResponse.data.data));
              localStorage.setItem('permissions', JSON.stringify(userInfoResponse.data.data || []));
            } else {
              message.warning('获取用户信息失败');
            }
          } catch (error) {
            console.error('获取用户信息失败:', error);
            message.warning('获取用户信息失败，请重新登录');
            return;
          }

          // 记住账号
          if (rememberMe.value) {
            if (loginType.value === 'account') {
              localStorage.setItem('rememberedAccount', JSON.stringify({
                username: formData.username,
                merchant_code: formData.merchant_code,
                loginType: 'account'
              }));
            } else if (loginType.value === 'mobile') {
              localStorage.setItem('rememberedAccount', JSON.stringify({
                mobile: formData.mobile,
                merchant_code: formData.merchant_code,
                loginType: 'mobile'
              }));
            }
          } else {
            // 如果取消记住账号，则清除保存的信息
            localStorage.removeItem('rememberedAccount');
          }

          message.success('登录成功');
          router.push('/');
        } else {
          message.error(response.data.message || '登录失败');
        }
      } catch (error) {
        console.error('登录失败:', error);
        message.error(error.response?.data?.message || '登录失败，请检查网络连接');
      } finally {
        loading.value = false;
      }
    };

    // 处理权限数据
    const processPermissions = (permissions = []) => {
      const auth = {};
      permissions.filter(item => item.type === 'btn').forEach(item => {
        if(auth[item.path]) {
          auth[item.path][item.key] = true;
        } else {
          auth[item.path] = {
            [item.key]: true
          };
        }
      });
      return auth;
    };

    // 初始化时从本地存储获取记住的信息
    const initRememberedAccount = () => {
      const rememberedAccount = localStorage.getItem('rememberedAccount');
      if (rememberedAccount) {
        try {
          const accountInfo = JSON.parse(rememberedAccount);
          rememberMe.value = true;
          
          if (accountInfo.loginType === 'account') {
            loginType.value = 'account';
            formData.username = accountInfo.username;
            /* formData.merchant_code = accountInfo.merchant_code; */
          } else if (accountInfo.loginType === 'mobile') {
            loginType.value = 'mobile';
            formData.mobile = accountInfo.mobile;
            /* formData.merchant_code = accountInfo.merchant_code; */
          }
        } catch (error) {
          console.error('解析记住的账号信息失败:', error);
          localStorage.removeItem('rememberedAccount');
        }
      }
    };

    // 清除记住的账号信息
    const clearRememberedAccount = () => {
      localStorage.removeItem('rememberedAccount');
      rememberMe.value = false;
      message.success('已清除记住的账号信息');
    };

    // 监听记住账号复选框变化
    watch(rememberMe, (newValue) => {
      if (!newValue) {
        clearRememberedAccount();
      }
    });

    // 在组件挂载时初始化记住的账号信息
    onMounted(() => {
      initRememberedAccount();
    });

    // 切换到手机号登录
    const switchToMobileLogin = () => {
      loginType.value = 'mobile';
      // 清空之前的登录表单数据
      formData.username = '';
      formData.password = '';
      // 如果之前保存过手机号，则自动填充
      const savedMobile = localStorage.getItem('mobile');
      if (savedMobile) {
        formData.mobile = savedMobile;
      }
      // 重置表单验证状态
      nextTick(() => {
        loginForm.value?.resetFields();
      });
      // 显示切换提示
      message.info('已切换到手机号登录模式');
    };

    // 切换到账号密码登录
    const switchToAccountLogin = () => {
      loginType.value = 'account';
      // 清空之前的登录表单数据
      formData.mobile = '';
      formData.verification_code = '';
      // 如果之前保存过手机号，则自动填充
      const savedMobile = localStorage.getItem('mobile');
      if (savedMobile) {
        formData.mobile = savedMobile;
      } 
      // 重置表单验证状态
      nextTick(() => {
        loginForm.value?.resetFields();
      });
      // 显示切换提示
      message.info('已切换到账号密码登录模式');
    };

    // 切换到微信登录
    const switchToWechatLogin = async () => {
      loginType.value = 'wechat';
      // 清空之前的登录表单数据
      formData.username = '';
      formData.password = '';
      formData.mobile = '';
      formData.verification_code = '';
      // 获取微信二维码
      await getWechatQrCode();
      // 重置表单验证状态
      nextTick(() => {
        loginForm.value?.resetFields();
      });
      message.info('已切换到微信扫码登录模式');
    };

    // 微信登录相关状态
    const wechatLoginModal = ref(false);
    const wechatQrCode = ref('');
    const wechatState = ref('');
    let wechatLoginTimer = null;

    // 获取微信登录二维码
    const getWechatQrCode = async () => {
      try {
        const response = await axios.get(`${import.meta.env.VITE_BASE_AI_API}/api/user/wechat/qrcode`);
        if (response.data.code === 200) {
          wechatQrCode.value = response.data.data.qrcode_url;
          wechatState.value = response.data.data.state;
          startWechatLoginCheck();
        } else {
          message.error('获取微信二维码失败');
        }
      } catch (error) {
        console.error('获取微信二维码失败:', error);
        message.error('获取微信二维码失败，请稍后重试');
      }
    };

    // 开始轮询检查微信登录状态
    const startWechatLoginCheck = () => {
      wechatLoginTimer = setInterval(async () => {
        try {
          const response = await axios.get(`${import.meta.env.VITE_BASE_AI_API}/api/user/wechat/check_login`, {
            params: { state: wechatState.value }
          });
          
          if (response.data.code === 200) {
            // 登录成功
            clearInterval(wechatLoginTimer);
            wechatLoginModal.value = false;
            
            // 保存token
            localStorage.setItem('token', response.data.data.token);
            
            // 获取并保存用户信息
            await getUserInfo(response.data.data.token);
            
            message.success('微信登录成功');
            router.push('/');
          }
        } catch (error) {
          console.error('检查微信登录状态失败:', error);
        }
      }, 2000); // 每2秒检查一次
    };

    // 关闭微信登录弹窗
    const handleWechatLoginCancel = () => {
      wechatLoginModal.value = false;
      if (wechatLoginTimer) {
        clearInterval(wechatLoginTimer);
        wechatLoginTimer = null;
      }
    };

    // 获取用户信息的公共方法
    const getUserInfo = async (token) => {
      try {
        const userInfoResponse = await axios.get(`${import.meta.env.VITE_BASE_AI_API}/user/info`, {
          headers: {
            'Authorization': `JWT ${token}`
          }
        });
        
        if (userInfoResponse.data.code === 200) {
          store.commit('app/setUser', {
            user: userInfoResponse.data.data.userInfo,
            permission: userInfoResponse.data.data.permissions || [],
            auth: processPermissions(userInfoResponse.data.data.permissions)
          });
        } else {
          message.warning('获取用户信息失败');
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        message.warning('获取用户信息失败，请重新登录');
        throw error;
      }
    };

    // 组件卸载时清理定时器
    onUnmounted(() => {
      if (wechatLoginTimer) {
        clearInterval(wechatLoginTimer);
        wechatLoginTimer = null;
      }
    });

    return {
      loginForm,
      formData,
      rules,
      loading,
      rememberMe,
      loginType,
      countdown,
      handleLogin,
      sendVerificationCode,
      switchToMobileLogin,
      switchToAccountLogin,
      switchToWechatLogin,
      wechatLoginModal,
      wechatQrCode,
      getWechatQrCode,
      handleWechatLoginCancel,
      clearRememberedAccount
    };
  }
});
</script>

<style lang="less" scoped>
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  
  .login-container {
    width: 100%;
    max-width: 420px;
    margin: 0 20px;
  }
  
  .login-content {
    background: rgba(255, 255, 255, 0.95);
    padding: 40px;
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(31, 38, 135, 0.15);
    backdrop-filter: blur(8px);
    animation: slideUp 0.6s ease-out;
  }
  
  .login-header {
    text-align: center;
    margin-bottom: 32px;
    
    h2 {
      font-size: 28px;
      color: #1a1a1a;
      margin-bottom: 8px;
      font-weight: 600;
    }
    
    .sub-title {
      color: #666;
      font-size: 14px;
    }
  }
  
  .form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .forgot-password {
      color: #667eea;
      font-size: 14px;
      transition: color 0.3s;
      
      &:hover {
        color: #764ba2;
      }
    }
  }
  
  .verification-code-input {
    display: flex;
    gap: 8px;

    .ant-input-affix-wrapper {
      flex: 1;
    }

    .ant-btn {
      min-width: 120px;
    }
  }
  
  .login-footer {
    margin-top: 32px;
    text-align: center;
    
    .register-tip {
      color: #666;
      font-size: 14px;
      margin-bottom: 24px;
      
      .register-link {
        color: #667eea;
        font-weight: 500;
        margin-left: 4px;
        
        &:hover {
          color: #764ba2;
        }
      }
    }
    
    // 更新登录方式切换的样式
    .login-type-switch {
      margin-bottom: 24px;

      .switch-title {
        color: #666;
        font-size: 14px;
        margin-bottom: 12px;
      }

      .ant-radio-group {
        display: flex;
        justify-content: center;
        gap: 12px;
      }

      .ant-radio-button-wrapper {
        border-radius: 4px;
        
        &:first-child {
          border-radius: 4px;
        }
        
        &:last-child {
          border-radius: 4px;
        }
      }
    }
    
    .divider {
      position: relative;
      text-align: center;
      margin: 16px 0;
      
      &::before,
      &::after {
        content: '';
        position: absolute;
        top: 50%;
        width: 30%;
        height: 1px;
        background: #e8e8e8;
      }
      
      &::before {
        left: 0;
      }
      
      &::after {
        right: 0;
      }
      
      span {
        background: #fff;
        padding: 0 12px;
        color: #999;
        font-size: 12px;
      }
    }
    
    .social-login {
      display: flex;
      justify-content: center;
      gap: 24px;
      margin-top: 16px;
      
      .social-icon {
        font-size: 24px;
        color: #666;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          color: #667eea;
          transform: scale(1.1);
        }

        // 为手机图标添加特殊样式
        &.mobile-active {
          color: #667eea;
        }
      }
    }
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式适配
@media (max-width: 480px) {
  .login-content {
    padding: 24px;
  }
  
  .login-header h2 {
    font-size: 24px;
  }
}

.wechat-qrcode-container {
  text-align: center;
  padding: 20px 0;

  .wechat-qrcode {
    width: 200px;
    height: 200px;
    margin-bottom: 16px;
  }

  .qrcode-tip {
    color: #666;
    font-size: 14px;
  }
}

.wechat-login-container {
  padding: 20px 0;
  text-align: center;

  .wechat-qrcode-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    background: #f5f5f5;
    border-radius: 8px;

    .wechat-qrcode {
      width: 200px;
      height: 200px;
      margin-bottom: 16px;
      border-radius: 4px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .qrcode-tip {
      color: #333;
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 8px;
    }

    .qrcode-sub-tip {
      color: #666;
      font-size: 14px;
    }
  }

  .qrcode-loading {
    padding: 60px 0;
  }
}

// 修改社交图标样式
.social-login {
  .social-icon {
    &.active {
      color: #667eea;
    }
  }
}
</style>
