<template>
  <div class="login-container">
    <div class="login-left">
      <div class="logo-section">
        <div class="logo">
          <div class="logo-icon">TS</div>
          <div class="logo-text">
            <div class="logo-chinese">数通达</div>
            <div class="logo-english">DIGITAL ACCESS</div>
          </div>
        </div>
      </div>
      <div class="welcome-section">
        <!-- <div class="welcome-title">Hi, 欢迎进入</div>
        <div class="welcome-subtitle">数智科创·通达未来</div> -->
        <img style="width: 88%;" src="@/assets/ziti.png" alt="">
      </div>
      <div class="description-section">
        <div class="description-line">深耕智能化科创服务</div>
        <div class="description-line">构建「数据驱动+技术赋能」的一站式科创云平台</div>
      </div>
      
    </div>
    <div class="login-right">
      <div class="login-card">
        <div class="login-title">Hi, 请登录</div>
        <div class="login-tabs">
          <div 
            class="tab-item" 
            :class="{ active: activeTab === 'password' }"
            @click="activeTab = 'password'"
          >
            密码登录
          </div>
          <div 
            class="tab-item" 
            :class="{ active: activeTab === 'phone' }"
            @click="activeTab = 'phone'"
          >
            手机登录
          </div>
        </div>
        <div class="login-form">
          <div class="form-item">
            <el-input
              v-model="loginForm.username"
              :placeholder="activeTab === 'password' ? '请输入账号...' : '请输入手机号'"
              size="large"
              prefix-icon="el-icon-user"
            ></el-input>
          </div>
          <div class="form-item" v-if="activeTab === 'password'">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码..."
              size="large"
              prefix-icon="el-icon-lock"
              :show-password="true"
            ></el-input>
          </div>
          <div class="form-item" v-if="activeTab === 'phone'">
            <el-input
              v-model="loginForm.phoneCode"
              placeholder="请输入验证码"
              size="large"
              prefix-icon="el-icon-message"
            >
              <template slot="append">
                <el-button @click="sendCode" :disabled="codeCountdown > 0">
                  {{ codeCountdown > 0 ? `${codeCountdown}秒` : '获取验证码' }}
                </el-button>
              </template>
            </el-input>
          </div>
          <div class="verification-section" v-if="activeTab === 'password'">
            <div 
              class="slider-verification" 
              @mousedown="startDrag"
              @mousemove="onDrag"
              @mouseup="endDrag"
              @mouseleave="endDrag"
            >
              <div class="slider-track">
                <div 
                  class="slider-handle" 
                  :class="{ 'verified': isVerified }" 
                  :style="{ left: isVerified ? 'calc(100% - 50px)' : sliderPosition + 'px' }"
                >
                  <i class="el-icon-right" v-if="!isVerified"></i>
                  <i class="el-icon-check" v-if="isVerified"></i>
                </div>
                <span class="slider-text" :class="{ 'hidden': isVerified || sliderPosition > 0 }">请拖动滑动验证</span>
                <span class="slider-success" v-if="isVerified">验证通过</span>
              </div>
            </div>
          </div>
          <div class="form-item login-btn-item">
            <el-button 
              type="primary" 
              class="login-btn"
              @click="handleLogin"
              :loading="loading"
            >
              登录
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { login, smsLogin, sendSmsCode, details } from '@/api/login/login'
import { setToken, getToken, setEnterpriseLogo } from '@/utils/auth'

export default {
  name: 'Login',
  data() {
    return {
      activeTab: 'password',
      loginForm: {
        username: '18286593512',
        password: 'admin',
        phoneCode: ''
      },
      isVerified: false,
      codeCountdown: 0,
      loading: false,
      sliderPosition: 0,
      isDragging: false
    }
  },
  methods: {
    startDrag(e) {
      if (this.isVerified) return
      this.isDragging = true
      this.onDrag(e)
    },
    onDrag(e) {
      if (!this.isDragging || this.isVerified) return
      const slider = e.currentTarget
      const rect = slider.getBoundingClientRect()
      const x = e.clientX - rect.left
      const maxX = rect.width - 50
      this.sliderPosition = Math.max(0, Math.min(x, maxX))
      
      // 如果拖到最右边，自动完成验证
      if (this.sliderPosition >= maxX - 5) {
        this.isVerified = true
        this.sliderPosition = maxX
        this.$message.success('验证通过')
        this.isDragging = false
      }
    },
    endDrag() {
      if (!this.isDragging) return
      this.isDragging = false
      // 如果没有完成验证，滑块回到起始位置
      if (!this.isVerified) {
        this.sliderPosition = 0
      }
    },
    async sendCode() {
      if (this.codeCountdown > 0) return
      if (!this.loginForm.username) {
        this.$message.warning('请输入手机号')
        return
      }
      try {
        await sendSmsCode({ phone: this.loginForm.username })
        this.$message.success('验证码已发送')
        this.codeCountdown = 60
        const timer = setInterval(() => {
          this.codeCountdown--
          if (this.codeCountdown <= 0) {
            clearInterval(timer)
          }
        }, 1000)
      } catch (error) {
        // 错误信息已在响应拦截器中处理
        console.error('发送验证码失败:', error)
      }
    },
    async handleLogin() {
      if (this.activeTab === 'password') {
        if (!this.loginForm.username || !this.loginForm.password) {
          this.$message.warning('请输入用户名和密码')
          return
        }
        if (!this.isVerified) {
          this.$message.warning('请先完成验证')
          return
        }
      } else {
        if (!this.loginForm.username || !this.loginForm.phoneCode) {
          this.$message.warning('请输入手机号和验证码')
          return
        }
      }
      
      this.loading = true
      try {
        let response
        if (this.activeTab === 'password') {
          // 密码登录
          response = await login({
            username: this.loginForm.username,
            password: this.loginForm.password
          })
        } else {
          // 短信验证码登录
          response = await smsLogin({
            phone: this.loginForm.username,
            code: this.loginForm.phoneCode
          })
        }
        
        // 登录成功，保存token
        // 响应结构: { code: 1, msg: "登陆成功!", data: { code: 1, data: { token: "...", user_id: 1, expire_time: 0, nickname: "...", logo: "..." } } }
        if (response && response.code === 1 && response.data) {
          // 处理嵌套的data结构
          let userData = response.data
          // 如果data里面还有data，取内层的data
          if (userData.data && userData.data.token) {
            userData = userData.data
          }
          
          // 保存token
          if (userData.token) {
            setToken(userData.token)
          }
          // 保存登录状态
          localStorage.setItem('isLogin', 'true')
          // 可选：保存用户ID
          if (userData.user_id) {
            localStorage.setItem('userId', userData.user_id)
          }
          // 保存用户昵称
          if (userData.nickname) {
            localStorage.setItem('userNickname', userData.nickname)
          }
          // 保存消息数量
          if (userData.msgCount !== undefined) {
            localStorage.setItem('msgCount', userData.msgCount)
          }
          // 保存企业LOGO
          if (userData.logo) {
            setEnterpriseLogo(userData.logo)
          }
          // 调用 details 接口获取用户详细信息（包括手机号）
          if (userData.user_id) {
            try {
              const detailRes = await details(userData.user_id)
              if (detailRes && detailRes.code === 1 && detailRes.data) {
                // 保存手机号
                if (detailRes.data.phone) {
                  localStorage.setItem('userPhone', detailRes.data.phone)
                }
                // 如果详情接口返回了logo，也保存（可能更准确）
                if (detailRes.data.logo) {
                  setEnterpriseLogo(detailRes.data.logo)
                }
              }
            } catch (error) {
              console.error('获取用户详情失败:', error)
            }
          }
          // 清除上一次的路由和菜单状态，确保登录后显示正确的菜单
          localStorage.removeItem('lastRoute')
          localStorage.removeItem('activeItemIndex')
          localStorage.removeItem('activeMenu')
          localStorage.removeItem('openedMenus')
          // 显示成功消息
          this.$message.success(response.msg || '登录成功')
          // 跳转到主页
          this.$router.push('/home')
        } else {
          // 登录失败
          this.$message.error(response?.msg || '登录失败，请重试')
        }
      } catch (error) {
        // 错误信息已在响应拦截器中处理
        console.error('登录失败:', error)
      } finally {
        this.loading = false
      }
    }
  },
  mounted() {
    // 如果已经登录，直接跳转
    if (getToken()) {
      this.$router.push('/home')
    }
  }
}
</script>

<style scoped>
/* 引入字体 - 当字体文件准备好后取消注释 */
/* 
@font-face {
  font-family: 'Fontquan-XinYiGuanHeiTi-Regular';
  src: url('../../assets/fonts/Fontquan-XinYiGuanHeiTi-Regular.woff2') format('woff2'),
       url('../../assets/fonts/Fontquan-XinYiGuanHeiTi-Regular.woff') format('woff'),
       url('../../assets/fonts/Fontquan-XinYiGuanHeiTi-Regular.ttf') format('truetype'),
       url('../../assets/fonts/Fontquan-XinYiGuanHeiTi-Regular.otf') format('opentype');
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}
*/

.login-container {
  display: flex;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  position: relative;
  background-image: url('../../assets/banner.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.login-left {
  flex: 1;
  position: relative;

  flex-direction: column;
  padding: 60px 80px;
  color: white;
  overflow: hidden;

}

.login-left::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(81, 101, 247, 0.85) 0%, rgba(61, 79, 216, 0.85) 100%);
  z-index: -1;
}

.background-pattern {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    linear-gradient(45deg, rgba(255, 255, 255, 0.05) 25%, transparent 25%),
    linear-gradient(-45deg, rgba(255, 255, 255, 0.05) 25%, transparent 25%),
    linear-gradient(45deg, transparent 75%, rgba(255, 255, 255, 0.05) 75%),
    linear-gradient(-45deg, transparent 75%, rgba(255, 255, 255, 0.05) 75%);
  background-size: 60px 60px;
  background-position: 0 0, 0 30px, 30px -30px, -30px 0px;
  opacity: 0.3;
  z-index: 2;
}

.logo-section {
  position: relative;
  z-index: 3;
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  width: 60px;
  height: 60px;
  background: transparent;
  border-radius: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36px;
  font-weight: bold;
  color: white;
  font-family: 'Arial', sans-serif;
  letter-spacing: -2px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
  line-height: 1;
}

.logo-text {
  display: flex;
  flex-direction: column;
}

.logo-chinese {
  font-size: 28px;
  font-weight: bold;
  line-height: 1.2;
}

.logo-english {
  font-size: 14px;
  opacity: 0.9;
  letter-spacing: 2px;
  margin-top: 4px;
}

.welcome-section {
  position: relative;
  z-index: 3;
margin-top: 120px;
}

.welcome-title {
  font-size: 48px;
  font-weight: 300;
  margin-bottom: 16px;
  line-height: 1.2;
  /* 字体文件准备好后取消注释 */
  /* font-family: 'Fontquan-XinYiGuanHeiTi-Regular', sans-serif; */
}

.welcome-subtitle {
  font-size: 32px;
  font-weight: 500;
  line-height: 1.2;
  /* 字体文件准备好后取消注释 */
  /* font-family: 'Fontquan-XinYiGuanHeiTi-Regular', sans-serif; */
}

.description-section {
  position: relative;
  z-index: 3;
  margin-top: 32px;
}

.description-line {
  font-size: 16px;
  line-height: 1.8;
  opacity: 0.9;
  margin-bottom: 8px;
}

.login-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  position: relative;
  z-index: 2;
}

.login-card {
  width: 100%;
  max-width: 480px;
  background: white;
  border-radius: 16px;
  padding: 48px 40px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.login-title {
  font-size: 28px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 32px;
  text-align: center;
}

.login-tabs {
  display: flex;
  border-bottom: 2px solid #e4e7ed;
  margin-bottom: 32px;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  font-size: 16px;
  color: #909399;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.tab-item:hover {
  color: #5165f7;
}

.tab-item.active {
  color: #5165f7;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  right: 0;
  height: 2px;
  background: #5165f7;
}

.login-form {
  width: 100%;
}

.form-item {
  margin-bottom: 24px;
}

.form-item:last-child {
  margin-bottom: 0;
}

::v-deep .el-input__inner {
  height: 48px;
  line-height: 48px;
  border-radius: 8px;
  border: 1px solid #dcdfe6 !important;
  font-size: 14px;
}

::v-deep .el-input__inner:focus {
  border-color: #5165f7;
}

::v-deep .el-input__prefix {
  left: 16px;
}

::v-deep .el-input--prefix .el-input__inner {
  padding-left: 48px;
}

.verification-section {
  margin-bottom: 24px;
}

.slider-verification {
  width: 100%;
  height: 48px;
  position: relative;
  cursor: grab;
  user-select: none;
}

.slider-verification:active {
  cursor: grabbing;
}

.slider-track {
  width: 88%;
  height: 100%;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding-left: 60px;
  overflow: hidden;
}

.slider-handle {
  position: absolute;
  left: 0;
  top: 0;
  width: 50px;
  height: 100%;
  background: #5165f7;
  border-radius: 8px 0 0 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  transition: all 0.3s ease;
  z-index: 2;
  cursor: grab;
}

.slider-handle:active {
  cursor: grabbing;
}

.slider-handle.verified {
  background: #67c23a;
  border-radius: 8px;
  left: calc(100% - 50px) !important;
}

.slider-text {
  font-size: 14px;
  color: #909399;
  transition: opacity 0.3s;
  z-index: 1;
  white-space: nowrap;
}

.slider-text.hidden {
  opacity: 0;
}

.slider-success {
  position: absolute;
  right: 16px;
  font-size: 14px;
  color: #67c23a;
  font-weight: 500;
  z-index: 1;
}

.login-btn-item {
  margin-top: 32px;
}

.login-btn {
  width: 100%;
  height: 48px;
  border-radius: 8px;
  font-size: 16px;
  background: #5165f7;
  border: none;
}

.login-btn:hover {
  background: #3d4fd8;
}

::v-deep .el-input-group__append {
  background: #5165f7;
  color: white;
  border: none;
  border-radius: 0 8px 8px 0;
  padding: 0 20px;
}

::v-deep .el-input-group__append .el-button {
  color: white;
  border: none;
  background: transparent;
}

::v-deep .el-input-group__append .el-button:hover {
  background: rgba(255, 255, 255, 0.1);
}

::v-deep .el-input-group__append .el-button:disabled {
  color: rgba(255, 255, 255, 0.6);
}
</style>

