<template>
  <view class="page-container">
    <view class="welcome-title">
      超吉炫，欢迎您！
    </view>

    <view class="main-card">
      <image class="logo" :src="imgurl+'/cjx/hexiao/lobin_lobin.png'" mode="aspectFit"></image>

      <view class="user-type-selector">
        <view
            class="type-button"
            :class="{ 'active': userType === 'distributor' }"
            @click="switchUserType('distributor')"
        >
          <uni-icons type="person" :color="userType === 'distributor' ? '#fff' : '#4a8af4'" size="20"></uni-icons>
          <text>经销商</text>
        </view>
        <view
            class="type-button"
            :class="{ 'active': userType === 'salesman' }"
            @click="switchUserType('salesman')"
        >
          <uni-icons type="staff" :color="userType === 'salesman' ? '#fff' : '#4a8af4'" size="20"></uni-icons>
          <text>业务员</text>
        </view>
      </view>

      <view class="form-group">
        <view class="input-wrapper">
          <uni-icons type="person" size="24" color="#cccccc"></uni-icons>
          <input class="input-field" type="number" v-model="phone" placeholder="请输入手机号" placeholder-class="placeholder" />
        </view>

        <view class="input-wrapper">
          <uni-icons type="locked" size="24" color="#cccccc"></uni-icons>
          <input class="input-field" type="number" v-model="code" placeholder="请输入验证码" placeholder-class="placeholder" />
          <text
              class="code-btn"
              :class="{ 'disabled': isCountingDown }"
              @click="getVerificationCode"
          >
            {{ codeBtnText }}
          </text>
        </view>
      </view>

      <button class="login-btn" @click="handleLogin">登 录</button>

<!--      <view class="version-info">-->
<!--        版本号：V1.0.0-->
<!--      </view>-->
    </view>
  </view>
</template>

<script>
// 1. 导入你的API方法
import { getVerificationCode, login } from '@/api/hexiao.js';
import {getAdminInfo, getAdminToken, setAdminInfo, setAdminToken} from "../../../utils/auth";

export default {
  data() {
    return {
      userType: 'distributor',
      phone: '',
      code: '',
      codeBtnText: '获取手机验证码',
      isCountingDown: false,
      countdown: 60,
      timer: null,
      imgurl:"https://hyscancode.oss-cn-hangzhou.aliyuncs.com/xiaochengxu",

    }
  },
  onUnload() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },
  onLoad(){
    let token = getAdminToken()
    if(token){
      this.doLoginSuccess();
    }
  },
  methods: {
    doLoginSuccess(){

      let info = getAdminInfo()
      let userType = info.roleType;
      let pageUrl = '/pages/cjx/hexiao/ywy/index';
      if(userType === 1){
        pageUrl = '/pages/cjx/hexiao/jxs/index';
      }
      if(userType === 2){
         pageUrl = '/pages/cjx/hexiao/ywy/index';
      }
      uni.reLaunch({
        url: pageUrl
      });
    },
    switchUserType(type) {
      this.userType = type;
    },

    // --- 更新：调用获取验证码的API ---
    getVerificationCode() {
      if (this.isCountingDown) {
        return;
      }
      if(!this.phone) {
        uni.showToast({ title: '请输入手机号', icon: 'none' });
        return;
      }
      if(this.timer){
        clearInterval(this.timer);
        this.timer = null;
      }

      let userType = 0;
      if(this.userType === 'distributor'){
        userType = 1;
      }
      if(this.userType === 'salesman'){
        userType = 2;
      }

      // 调用API
      getVerificationCode(this.phone,userType).then(res => {
        if(res.code !== 0){
          uni.showToast({ title: res.msg || '找不到用户信息，请确认', icon: 'none' });
          return;
        }
        console.log('验证码接口成功返回:', res);
        uni.showToast({ title: res.msg || '验证码已发送', icon: 'success' });

        // 开始倒计时
        this.isCountingDown = true;
        this.codeBtnText = `${this.countdown}s后重新获取`;
        this.timer = setInterval(() => {
          this.countdown--;
          if (this.countdown > 0) {
            this.codeBtnText = `${this.countdown}s后重新获取`;
          } else {
            clearInterval(this.timer);
            this.timer = null;
            this.countdown = 60;
            this.isCountingDown = false;
            this.codeBtnText = '获取手机验证码';
          }
        }, 1000);

      }).catch(err => {
        // if(res.code === -99){
        //   uni.showToast({ title: err.msg || '找不到用户信息，请确认', icon: 'none' });
        //   return;
        // }
        // console.error('验证码接口失败返回:', err);
        // uni.showToast({ title: err.msg || '发送失败，请重试', icon: 'none' });
      });
    },
    setUserInfo(res){
      setAdminInfo(res);
    },
    // --- 更新：调用登录的API ---
    handleLogin() {
      if(!this.phone || !this.code) {
        uni.showToast({ title: '请填写完整信息', icon: 'none' });
        return;
      }

      uni.showLoading({ title: '登录中...' });
      let userType = 0;
      if(this.userType === 'distributor'){
        userType = 1;
      }
      if(this.userType === 'salesman'){
        userType = 2;
      }
      let self = this;
      uni.login({
        provider: 'weixin', //使用微信登录
        success: function (loginRes) {
          let jsCode = loginRes.code;
          login(self.phone, self.code,userType,jsCode).then(res => {
            // 登录成功 (res.code === 0)
            uni.hideLoading();

            if (res.code === 0) {
              setAdminToken(res.data.sessionId)
              self.setUserInfo(res.data);
              self.doLoginSuccess();
            } else {
              console.log('登录失败！' + res.msg);
              uni.showToast({ title: err.msg || '登录失败', icon: 'none' });
            }
          }).catch(err => {
            // 登录失败 (res.code !== 0 或网络错误)
            uni.hideLoading();
            console.error('登录失败:', err);
            uni.showToast({ title: err.msg || '登录失败', icon: 'none' });
          });
        }
      });
      // 调用API

    }
  }
}
</script>

<style lang="scss">
.page-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: hidden;
  min-height: 100vh;
  background-image: url("https://hyscancode.oss-cn-hangzhou.aliyuncs.com/xiaochengxu/cjx/hexiao/login_bg.png");
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
}

.welcome-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #488CFF;
  margin-top: 28%;
  margin-bottom: 40rpx;
}

.main-card {
  width: 88%;
  border-radius: 40rpx;
  padding: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  top: 10%;
  height: 100%;
}

.logo {
  width: 150rpx;
  height: 150rpx;
  background-color: #f0f0f0;
  margin-bottom: 40rpx;
  border-radius: 20rpx;
}

.user-type-selector {
  display: flex;
  justify-content: center;
  width: 100%;
  margin-bottom: 50rpx;

  .type-button {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30rpx;
    padding: 15rpx 40rpx;
    border-radius: 50rpx;
    transition: all 0.3s ease;
    border: 1px solid #4a8af4;
    color: #4a8af4;
    background-color: #fff;
    margin: 0 15rpx;

    .uni-icons {
      margin-right: 10rpx;
    }

    &.active {
      background-color: #4a8af4;
      color: #ffffff;
      border-color: #4a8af4;
    }
  }
}

.form-group {
  width: 100%;
}

.input-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 20rpx 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 30rpx;

  .input-field {
    flex: 1;
    font-size: 30rpx;
    margin-left: 20rpx;
  }

  .placeholder {
    color: #cccccc;
  }

  .code-btn {
    font-size: 28rpx;
    color: #4a8af4;
    white-space: nowrap;
    padding-left: 20rpx;
    transition: color 0.3s; // 添加颜色过渡效果

    // --- 新增：置灰样式 ---
    &.disabled {
      color: #cccccc;
    }
  }
}

.login-btn {
  width: 100%;
  background: #4a8af4;
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 50rpx;
  margin-top: 40rpx;
  box-shadow: 0 10rpx 20rpx rgba(74, 138, 244, 0.3);
}

.version-info {
  margin-top: 40rpx;
  font-size: 24rpx;
  color: #b0b0b0;
}
</style>
