<template>
  <view class="login-container">
    <!-- 背景装饰 -->
    <view class="background-decoration">
      <view class="decoration-circle circle-1"></view>
      <view class="decoration-circle circle-2"></view>
      <view class="decoration-circle circle-3"></view>
    </view>
    
    <!-- 登录内容 -->
    <view class="login-content">
      <!-- Logo和标题 -->
      <view class="login-header">
        <image class="logo" src="/static/images/logo.png" mode="aspectFit"></image>
        <text class="app-name">养殖管理</text>
        <text class="app-slogan">智慧畜牧，科学养殖</text>
      </view>
      
      <!-- 登录表单 -->
      <view class="login-form">
        <!-- 手机号输入 -->
        <view class="form-item">
          <view class="input-wrapper">
            <text class="input-icon">📱</text>
            <input 
              class="form-input"
              type="number"
              placeholder="请输入手机号"
              v-model="formData.phone"
              maxlength="11"
              @input="onPhoneInput"
            />
          </view>
          <text class="error-text" v-if="errors.phone">{{ errors.phone }}</text>
        </view>
        
        <!-- 验证码输入 -->
        <view class="form-item">
          <view class="input-wrapper">
            <text class="input-icon">🔐</text>
            <input 
              class="form-input code-input"
              type="number"
              placeholder="请输入验证码"
              v-model="formData.code"
              maxlength="6"
            />
            <button 
              class="code-button" 
              :class="{ 'disabled': codeDisabled }"
              :disabled="codeDisabled"
              @tap="sendCode"
            >
              {{ codeText }}
            </button>
          </view>
          <text class="error-text" v-if="errors.code">{{ errors.code }}</text>
        </view>
        
        <!-- 登录按钮 -->
        <button 
          class="login-button"
          :class="{ 'disabled': !canLogin }"
          :disabled="!canLogin"
          @tap="handleLogin"
        >
          {{ loading ? '登录中...' : '登录' }}
        </button>
        
        <!-- 其他登录方式 -->
        <view class="other-login">
          <text class="other-text">其他登录方式</text>
          <view class="other-methods">
            <button class="wechat-login" @tap="wechatLogin">
              <text class="method-icon">🔐</text>
              <text class="method-text">微信登录</text>
            </button>
          </view>
        </view>
        
        <!-- 协议条款 -->
        <view class="agreement">
          <checkbox-group @change="onAgreementChange">
            <label class="agreement-item">
              <checkbox :checked="agreed" color="#2E8B57" />
              <text class="agreement-text">
                我已阅读并同意
                <text class="link-text" @tap="showPrivacy">《隐私政策》</text>
                和
                <text class="link-text" @tap="showTerms">《用户协议》</text>
              </text>
            </label>
          </checkbox-group>
        </view>
      </view>
    </view>
    
    <!-- 加载组件 -->
    <loading :show="loading" text="登录中..."></loading>
  </view>
</template>

<script>
import { validate } from '@/common/utils/validator'
import Loading from '@/common/components/loading/loading.vue'

export default {
  name: 'Login',
  
  components: {
    Loading
  },
  
  data() {
    return {
      formData: {
        phone: '',
        code: ''
      },
      errors: {},
      loading: false,
      agreed: false,
      codeDisabled: false,
      codeCountdown: 0,
      codeTimer: null
    }
  },
  
  computed: {
    canLogin() {
      return this.formData.phone && 
             this.formData.code && 
             this.agreed && 
             !this.loading
    },
    
    codeText() {
      return this.codeCountdown > 0 ? `${this.codeCountdown}s` : '获取验证码'
    }
  },
  
  onLoad() {
    this.checkAutoLogin()
  },
  
  onUnload() {
    if (this.codeTimer) {
      clearInterval(this.codeTimer)
    }
  },
  
  methods: {
    // 检查自动登录
    async checkAutoLogin() {
      const token = uni.getStorageSync('token')
      if (token) {
        try {
          // 验证token有效性
          const res = await this.$request({
            url: '/auth/validate',
            method: 'POST',
            loading: false
          })
          
          if (res.code === 200) {
            // token有效，直接跳转
            this.loginSuccess(res.data)
            return
          }
        } catch (error) {
          // token无效，清除本地存储
          uni.removeStorageSync('token')
          uni.removeStorageSync('userInfo')
        }
      }
    },
    
    // 手机号输入
    onPhoneInput() {
      this.validatePhone()
    },
    
    // 验证手机号
    validatePhone() {
      const phone = this.formData.phone
      if (!phone) {
        this.errors.phone = '请输入手机号'
        return false
      }
      
      if (!validate.phone(phone)) {
        this.errors.phone = '请输入正确的手机号'
        return false
      }
      
      delete this.errors.phone
      return true
    },
    
    // 发送验证码
    async sendCode() {
      if (!this.validatePhone()) {
        return
      }
      
      try {
        await this.$request({
          url: '/auth/send-code',
          method: 'POST',
          data: {
            phone: this.formData.phone
          }
        })
        
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
        
        // 开始倒计时
        this.startCountdown()
        
      } catch (error) {
        console.error('发送验证码失败：', error)
      }
    },
    
    // 开始倒计时
    startCountdown() {
      this.codeDisabled = true
      this.codeCountdown = 60
      
      this.codeTimer = setInterval(() => {
        this.codeCountdown--
        
        if (this.codeCountdown <= 0) {
          this.codeDisabled = false
          clearInterval(this.codeTimer)
          this.codeTimer = null
        }
      }, 1000)
    },
    
    // 处理登录
    async handleLogin() {
      if (!this.validateForm()) {
        return
      }
      
      this.loading = true
      
      try {
        const res = await this.$request({
          url: '/auth/login',
          method: 'POST',
          data: {
            phone: this.formData.phone,
            code: this.formData.code
          },
          loading: false
        })
        
        this.loginSuccess(res.data)
        
      } catch (error) {
        console.error('登录失败：', error)
      } finally {
        this.loading = false
      }
    },
    
    // 微信登录
    async wechatLogin() {
      if (!this.agreed) {
        uni.showToast({
          title: '请先同意用户协议',
          icon: 'none'
        })
        return
      }
      
      try {
        // 获取微信登录code
        const loginRes = await uni.login({
          provider: 'weixin'
        })
        
        if (loginRes.code) {
          this.loading = true
          
          const res = await this.$request({
            url: '/auth/wechat-login',
            method: 'POST',
            data: {
              code: loginRes.code
            },
            loading: false
          })
          
          this.loginSuccess(res.data)
        }
        
      } catch (error) {
        console.error('微信登录失败：', error)
        uni.showToast({
          title: '微信登录失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 登录成功
    loginSuccess(data) {
      // 保存用户信息和token
      uni.setStorageSync('token', data.token)
      uni.setStorageSync('userInfo', data.userInfo)
      
      // 设置全局数据
      getApp().globalData.token = data.token
      getApp().globalData.userInfo = data.userInfo
      
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      })
      
      // 跳转到首页
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/index/index'
        })
      }, 1500)
    },
    
    // 验证表单
    validateForm() {
      this.errors = {}
      let isValid = true
      
      // 验证手机号
      if (!this.validatePhone()) {
        isValid = false
      }
      
      // 验证验证码
      if (!this.formData.code) {
        this.errors.code = '请输入验证码'
        isValid = false
      } else if (this.formData.code.length !== 6) {
        this.errors.code = '请输入6位验证码'
        isValid = false
      }
      
      return isValid
    },
    
    // 协议变更
    onAgreementChange(e) {
      this.agreed = e.detail.value.length > 0
    },
    
    // 显示隐私政策
    showPrivacy() {
      uni.navigateTo({
        url: '/pages/legal/privacy'
      })
    },
    
    // 显示用户协议
    showTerms() {
      uni.navigateTo({
        url: '/pages/legal/terms'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  
  .decoration-circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    
    &.circle-1 {
      width: 300rpx;
      height: 300rpx;
      top: -150rpx;
      right: -150rpx;
    }
    
    &.circle-2 {
      width: 200rpx;
      height: 200rpx;
      bottom: 200rpx;
      left: -100rpx;
    }
    
    &.circle-3 {
      width: 150rpx;
      height: 150rpx;
      top: 300rpx;
      left: 50rpx;
    }
  }
}

.login-content {
  position: relative;
  z-index: 1;
  padding: 100rpx 60rpx 60rpx;
}

.login-header {
  text-align: center;
  margin-bottom: 100rpx;
  
  .logo {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 30rpx;
  }
  
  .app-name {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #ffffff;
    margin-bottom: 16rpx;
  }
  
  .app-slogan {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.login-form {
  .form-item {
    margin-bottom: 40rpx;
    
    .input-wrapper {
      position: relative;
      background: rgba(255, 255, 255, 0.95);
      border-radius: 16rpx;
      display: flex;
      align-items: center;
      padding: 0 30rpx;
      backdrop-filter: blur(10rpx);
      
      .input-icon {
        font-size: 32rpx;
        margin-right: 20rpx;
      }
      
      .form-input {
        flex: 1;
        height: 100rpx;
        font-size: 32rpx;
        color: #333333;
        
        &.code-input {
          padding-right: 160rpx;
        }
      }
      
      .code-button {
        position: absolute;
        right: 20rpx;
        height: 60rpx;
        padding: 0 20rpx;
        background: linear-gradient(135deg, #2E8B57, #3CB371);
        color: #ffffff;
        border: none;
        border-radius: 8rpx;
        font-size: 24rpx;
        
        &.disabled {
          background: #cccccc;
          color: #999999;
        }
        
        &::after {
          border: none;
        }
      }
    }
    
    .error-text {
      display: block;
      font-size: 24rpx;
      color: #ff6b6b;
      margin-top: 16rpx;
      margin-left: 30rpx;
    }
  }
  
  .login-button {
    width: 100%;
    height: 100rpx;
    background: linear-gradient(135deg, #2E8B57, #3CB371);
    color: #ffffff;
    border: none;
    border-radius: 16rpx;
    font-size: 36rpx;
    font-weight: 600;
    margin-bottom: 60rpx;
    
    &.disabled {
      background: rgba(255, 255, 255, 0.3);
      color: rgba(255, 255, 255, 0.6);
    }
    
    &::after {
      border: none;
    }
  }
}

.other-login {
  text-align: center;
  margin-bottom: 60rpx;
  
  .other-text {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
    margin-bottom: 30rpx;
    display: block;
  }
  
  .other-methods {
    .wechat-login {
      background: rgba(255, 255, 255, 0.95);
      border: none;
      border-radius: 16rpx;
      padding: 20rpx 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      backdrop-filter: blur(10rpx);
      
      .method-icon {
        font-size: 32rpx;
        margin-right: 16rpx;
      }
      
      .method-text {
        font-size: 32rpx;
        color: #333333;
      }
      
      &::after {
        border: none;
      }
    }
  }
}

.agreement {
  .agreement-item {
    display: flex;
    align-items: flex-start;
    
    .agreement-text {
      font-size: 24rpx;
      color: rgba(255, 255, 255, 0.8);
      line-height: 1.6;
      margin-left: 16rpx;
      
      .link-text {
        color: #ffffff;
        text-decoration: underline;
      }
    }
  }
}
</style>